//
//  DropboxMediaShareCommunity.m
//  MediaShareBB
//
//  Created by Artak Gevorgyan on 5/23/13.
//  Copyright (c) 2013 InnoriseEntertainment. All rights reserved.
//

#import "DropboxMediaShareCommunity.h"
#import "AppDelegate.h"
#import "MediaShareBBUtilityMethods.h"
#import "MediaShareData.h"

#import <DropboxSDK/DropboxSDK.h>

@interface DropboxMediaShareCommunity()<DBRestClientDelegate>
{
	NSString* _appKey;
	NSString* _appSecretKey;
	NSString* _root;
    NSString* _userName;
    NSString* _sharedFileLink;
	DBRestClient* _restClient;
	MediaShareData* _sharedMediaData;
    BOOL _isFinishedSharingMadia;
}

@end

@implementation DropboxMediaShareCommunity

-(id) init {
	self = [super init];
	if (self) {
		super.name = @"Dropbox";
		super.communityType = MEDIA_SHARE_COMMUNITY_DROPBOX;
		super.supportedMediaTypes = [[NSArray alloc] initWithObjects:
									 [NSNumber numberWithInt:IMAGE_MEDIA_TYPE],
									 [NSNumber numberWithInt:VIDEO_MEDIA_TYPE],
									 [NSNumber numberWithInt:URL_MEDIA_TYPE], nil];
	}
        return self;
}

#pragma mark - Superclass methods

// Superclass method
-(NSString*) description {
	NSString* d = @"Dropbox description";
	return d;
}

// Superclass method
-(void) configureWithCredentials:(NSDictionary*) credentials {
	_appKey = [credentials valueForKey:@"appKey"];
	_appSecretKey = [credentials valueForKey:@"secretKey"];
	[self initializeRootBasedOnFolderAccessMode:DROPBOX_APP_FOLDER_ACCESS_MODE];
	[self validateAppKey];
}

// Superclass method
-(void) login {
	if ([DBSession sharedSession] == nil) {
		DBSession* session = [[DBSession alloc] initWithAppKey:_appKey
													 appSecret:_appSecretKey
														  root:_root];
		session.delegate = self;
		[DBSession setSharedSession:session];
		[DBRequest setNetworkRequestDelegate:self];
	}
	if ([[NSUserDefaults standardUserDefaults] objectForKey:IS_LOGGED_IN_TO_DROPBOX] == nil) {
		[[DBSession sharedSession] unlinkAll];
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:@"DropboxLoginComplete"
                                                      object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(loginComplete:)
													 name:@"DropboxLoginComplete"
												   object:nil];
		AppDelegate* app = [UIApplication sharedApplication].delegate;
		[[DBSession sharedSession] linkFromController:app.window.rootViewController];
	} else {
		[self loginComplete:nil];
	}
}

//Superclass method
-(void) loginWithAnotherUser {
    [_restClient cancelAllRequests];
    _restClient = nil;
    [[DBSession sharedSession] unlinkAll];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"DropboxLoginComplete"
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginComplete:)
                                                 name:@"DropboxLoginComplete"
                                               object:nil];
    AppDelegate* app = [UIApplication sharedApplication].delegate;
    [[DBSession sharedSession] linkFromController:app.window.rootViewController];
}

//Superclass method
-(NSString*) getUserName {
    return _userName;
}

//Superclass method
-(NSString*) sharedMediaLink {
    return _sharedFileLink;
}

// Superclass method
-(void) shareMedia:(MediaShareData*) data {
	if ([super isValidMediaType:data.mediaType]) {
		_sharedMediaData = data;
		if ([MediaShareBBUtilityMethods isObject:super.delegate
							  respondsToSelector:@selector(willSharingMedia:through:)]) {
			[super.delegate willSharingMedia:_sharedMediaData through:self];
			if (IMAGE_MEDIA_TYPE == data.mediaType) {
				[self shareImage];
			}
            if (VIDEO_MEDIA_TYPE == data.mediaType) {
                [self shareVideo];
            }
		}
	} else {
		NSLog(@"%s: Unsupported media type:%d", __PRETTY_FUNCTION__, data.mediaType);
	}
}

#pragma mark - DBSessionDelegate methods

-(void) sessionDidReceiveAuthorizationFailure:(DBSession*) session
									   userId:(NSString*) userId {
	NSLog(@"%s: Authorization failed", __PRETTY_FUNCTION__);
	if ([MediaShareBBUtilityMethods isObject:super.delegate
						  respondsToSelector:@selector(loginFailedWithError:)]) {
		[super.delegate loginFailedWithError:nil];
	}
}

#pragma mark - DBNetworkRequestDelegate methods

static int outstandingRequests;

-(void) networkRequestStarted {
	outstandingRequests++;
	if (outstandingRequests == 1) {
		[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
	}
}

-(void) networkRequestStopped {
	outstandingRequests--;
	if (outstandingRequests == 0) {
		[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	}
}

#pragma mark - DBRestClientDelegate methods

-(void) restClient:(DBRestClient*) client uploadedFile:(NSString*) destPath
			  from:(NSString*) srcPath metadata:(DBMetadata*) metadata {
	NSLog(@"%s: Successfully uploaded at path: %@", __PRETTY_FUNCTION__, metadata.path);
	if ([MediaShareBBUtilityMethods isObject:super.delegate
						  respondsToSelector:@selector(didFinishSharingMedia:through:)]) {
        _isFinishedSharingMadia = YES;
//		[super.delegate didFinishSharingMedia:_sharedMediaData
//									  through:self];
	}
    NSString* str;
    if (_sharedMediaData.mediaType == VIDEO_MEDIA_TYPE) {
        str = @".mp4";
    } else {
        str = @".png";
    }
    [[self restClient] loadSharableLinkForFile:[NSString stringWithFormat:@"/%@%@",_sharedMediaData.fileName, str ]];
}

-(void) restClient:(DBRestClient*) client uploadFileFailedWithError:(NSError*) error {
    NSLog(@"%s: Upload failed with error: %@", __PRETTY_FUNCTION__, error);
	if ([MediaShareBBUtilityMethods isObject:super.delegate
						  respondsToSelector:@selector(didFailedSharingMedia:through:withError:)]) {
		[super.delegate didFailedSharingMedia:_sharedMediaData
									  through:self
									withError:error];
	}
}

-(void) restClient:(DBRestClient*) client loadedAccountInfo:(DBAccountInfo*) info {
        _userName = [info displayName];
	if ([MediaShareBBUtilityMethods isObject:super.delegate
						  respondsToSelector:@selector(loginSuccess)]) {
		[super.delegate loginSuccess];
	}
}

-(void) restClient:(DBRestClient*) restClient loadedSharableLink:(NSString*) link forFile:(NSString*) path {
    _sharedFileLink = link;
    if (_isFinishedSharingMadia) {
        _isFinishedSharingMadia = NO;
        [super.delegate didFinishSharingMedia:_sharedMediaData
									  through:self];
    }
}

-(void) restClient:(DBRestClient*) restClient loadSharableLinkFailedWithError:(NSError*) error {
    NSLog(@"%@", [error localizedDescription]);
}

#pragma mark - Private methods

// Notification from AppDelegate
-(void) loginComplete:(NSNotification*) notification {
	[[NSUserDefaults standardUserDefaults] setBool:YES
											forKey:IS_LOGGED_IN_TO_DROPBOX];
	[[NSUserDefaults standardUserDefaults] synchronize];
    [self.restClient loadAccountInfo];
}

-(DBRestClient*) restClient {
	if (!_restClient) {
		_restClient =
		[[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
		_restClient.delegate = self;
	}
	return _restClient;
}

-(void) initializeRootBasedOnFolderAccessMode:(enum DropboxFolderAccessMode) mode {
	switch (mode) {
		case DROPBOX_APP_FOLDER_ACCESS_MODE:
			_root = kDBRootAppFolder;
			break;
		case DROPBOX_FULL_FOLDER_ACCESS_MODE:
			_root = kDBRootDropbox;
			break;
		default:
			break;
	}
}

-(void) validateAppKey {
	NSString* errorMsg = nil;
	if ([_appKey rangeOfCharacterFromSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]].location != NSNotFound) {
		errorMsg = @"Make sure you set the app key correctly";
	} else if ([_appSecretKey rangeOfCharacterFromSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]].location != NSNotFound) {
		errorMsg = @"Make sure you set the app secret correctly";
	} else if ([_root length] == 0) {
		errorMsg = @"Set your root to use either App Folder of full Dropbox";
	} else {
		NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
		NSData* plistData = [NSData dataWithContentsOfFile:plistPath];
		NSDictionary* loadedPlist = [NSPropertyListSerialization
											 propertyListFromData:plistData
											 mutabilityOption:0
											 format:NULL
											 errorDescription:NULL];
		NSString* scheme = [[[[loadedPlist objectForKey:@"CFBundleURLTypes"] objectAtIndex:0]
											objectForKey:@"CFBundleURLSchemes"] objectAtIndex:0];
		if ([scheme isEqual:_appKey]) {
			errorMsg = @"Set your URL scheme correctly in plist file";
		}
	}
	if (errorMsg != nil) {
		NSLog(@"%s: Error Configuring Session: %@", __PRETTY_FUNCTION__, errorMsg);
	}
}

-(void) shareImage {
	NSString* s = [NSString stringWithFormat:@"%@.png", _sharedMediaData.fileName];
	NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:s];
	[_sharedMediaData.data writeToFile:file atomically:YES];
    [[self restClient] uploadFile:s
                           toPath:@"/"
                    withParentRev:nil
                         fromPath:file];
}

-(void) shareVideo {
	NSString* s = [NSString stringWithFormat:@"%@", _sharedMediaData.path];
	NSString* name = [NSString stringWithFormat:@"%@.mp4", _sharedMediaData.fileName];
	[[self restClient] uploadFile:name
                           toPath:@"/"
					withParentRev:nil
                         fromPath:s];
}

@end
